/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Telas;

import Beans.BeanCidade;
import Beans.BeanUsuario;
import CRUD.CRUDCidade;
import CRUD.CRUDUsuario;
import Conexao.ConexaoBanco;
import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Marcos
 */
public class Jp_CadastroUsuario extends javax.swing.JPanel {

    DefaultTableModel TMUsuario = new DefaultTableModel(null, new String[]{"Código", "Usuário", "", "Status"}) {// Faz a sobreposição de método e permite tbm a instancia de classe abstrata, quando implementado seus métodos
        @Override
        public boolean isCellEditable(int row, int column) {
            return false; //Não deixar editar uma linha da JTable
//            return super.isCellEditable(row, column);
        }
    };
    public Connection conexao;
    List<BeanUsuario> ListaUsuario;

    /**
     * Creates new form Jp_CadastroUsuario
     */
    public Jp_CadastroUsuario() throws SQLException {
        initComponents();
        AlinhaColunaJTable();
        this.conexao = ConexaoBanco.getConexao();
        jLabelCodUsuario.setText(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroupStatus = new javax.swing.ButtonGroup();
        jLabelUsuario = new javax.swing.JLabel();
        jLabelSenha = new javax.swing.JLabel();
        jTextFieldUsuario = new javax.swing.JTextField();
        jPasswordFieldSenha = new javax.swing.JPasswordField();
        jRadioButtonAtivo = new javax.swing.JRadioButton();
        jRadioButtonInativo = new javax.swing.JRadioButton();
        jButtonIncluir = new javax.swing.JButton();
        jButtonAlterar = new javax.swing.JButton();
        jLabelBarraStatus = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableConsultaUsuario = new javax.swing.JTable();
        jLabelCodUsuario = new javax.swing.JLabel();
        jButtonNovo = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabelUsuario.setText("*Usuario:");

        jLabelSenha.setText("*Senha:");

        jTextFieldUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextFieldUsuarioKeyPressed(evt);
            }
        });

        jPasswordFieldSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordFieldSenhaKeyPressed(evt);
            }
        });

        buttonGroupStatus.add(jRadioButtonAtivo);
        jRadioButtonAtivo.setSelected(true);
        jRadioButtonAtivo.setText("Ativo");

        buttonGroupStatus.add(jRadioButtonInativo);
        jRadioButtonInativo.setText("Inativo");

        jButtonIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Incluir.png"))); // NOI18N
        jButtonIncluir.setMnemonic('I');
        jButtonIncluir.setText("Incluir");
        jButtonIncluir.setToolTipText("Incluir");
        jButtonIncluir.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                jButtonIncluirMouseDragged(evt);
            }
        });
        jButtonIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonIncluirActionPerformed(evt);
            }
        });

        jButtonAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Alterar.png"))); // NOI18N
        jButtonAlterar.setMnemonic('A');
        jButtonAlterar.setText("Alterar");
        jButtonAlterar.setToolTipText("Alterar");
        jButtonAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAlterarActionPerformed(evt);
            }
        });

        jLabelBarraStatus.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabelBarraStatus.setForeground(new java.awt.Color(255, 0, 51));

        jTableConsultaUsuario.setModel(TMUsuario);
        jTableConsultaUsuario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableConsultaUsuarioMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTableConsultaUsuario);

        jButtonNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Novo.png"))); // NOI18N
        jButtonNovo.setMnemonic('N');
        jButtonNovo.setText("Novo");
        jButtonNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNovoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelBarraStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButtonNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonIncluir, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jRadioButtonAtivo)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jRadioButtonInativo)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)
                                    .addComponent(jLabelCodUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabelUsuario)
                                        .addComponent(jLabelSenha))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jPasswordFieldSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
                                        .addComponent(jTextFieldUsuario)))))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButtonAtivo)
                    .addComponent(jRadioButtonInativo)
                    .addComponent(jLabelCodUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 8, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelUsuario)
                    .addComponent(jTextFieldUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelSenha)
                    .addComponent(jPasswordFieldSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonIncluir)
                    .addComponent(jButtonAlterar)
                    .addComponent(jButtonNovo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelBarraStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonIncluirMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonIncluirMouseDragged
        //        jButtonIncluir.setLocation(jButtonIncluir.getX() + evt.getX(), jButtonIncluir.getY() + evt.getY());
    }//GEN-LAST:event_jButtonIncluirMouseDragged

    private void jButtonIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonIncluirActionPerformed
        if (jTextFieldUsuario.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "O campo usuário precisa ser preenchido!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jTextFieldUsuario.setBackground(new Color(255, 204, 204));
            jTextFieldUsuario.grabFocus();
        } else if (jPasswordFieldSenha.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "O campo senha precisa ser preenchido!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jPasswordFieldSenha.setBackground(new Color(255, 204, 204));
            jPasswordFieldSenha.grabFocus();
        } else {
            validausuariocadastro();
        }
    }//GEN-LAST:event_jButtonIncluirActionPerformed

    private void jTextFieldUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldUsuarioKeyPressed
        if (!"".equals(jTextFieldUsuario.getText())) {
        } else {
            jTextFieldUsuario.setBackground(new Color(255, 255, 255));
        }
        try {
            listausuario();
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jTextFieldUsuarioKeyPressed

    private void jPasswordFieldSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordFieldSenhaKeyPressed
        if (!"".equals(jPasswordFieldSenha.getText())) {
        } else {
            jPasswordFieldSenha.setBackground(new Color(255, 255, 255));
        }
    }//GEN-LAST:event_jPasswordFieldSenhaKeyPressed

    private void jButtonAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAlterarActionPerformed
        if (jTextFieldUsuario.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "O campo usuário precisa ser preenchido!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jTextFieldUsuario.setBackground(new Color(255, 204, 204));
            jTextFieldUsuario.grabFocus();
        } else if (jPasswordFieldSenha.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "O campo senha precisa ser preenchido!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jPasswordFieldSenha.setBackground(new Color(255, 204, 204));
            jPasswordFieldSenha.grabFocus();
        } else {
            altera();
        }
    }//GEN-LAST:event_jButtonAlterarActionPerformed

    private void jTableConsultaUsuarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableConsultaUsuarioMouseClicked
        if (evt.getClickCount() == 2) {
            carregardados();
        }
    }//GEN-LAST:event_jTableConsultaUsuarioMouseClicked

    private void jButtonNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNovoActionPerformed
        limpardados();
    }//GEN-LAST:event_jButtonNovoActionPerformed
    public void listausuario() throws SQLException, ParseException {
        CRUDUsuario CRUDUsu = new CRUDUsuario();
        ListaUsuario = CRUDUsu.getListaUsuarioNomLike("%" + jTextFieldUsuario.getText() + "%");
        mostraUsuario(ListaUsuario);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroupStatus;
    private javax.swing.JButton jButtonAlterar;
    private javax.swing.JButton jButtonIncluir;
    private javax.swing.JButton jButtonNovo;
    private javax.swing.JLabel jLabelBarraStatus;
    private javax.swing.JLabel jLabelCodUsuario;
    private javax.swing.JLabel jLabelSenha;
    private javax.swing.JLabel jLabelUsuario;
    private javax.swing.JPasswordField jPasswordFieldSenha;
    private javax.swing.JRadioButton jRadioButtonAtivo;
    private javax.swing.JRadioButton jRadioButtonInativo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableConsultaUsuario;
    private javax.swing.JTextField jTextFieldUsuario;
    // End of variables declaration//GEN-END:variables

    public void limpardados() {
        jTextFieldUsuario.setText(null);
        jPasswordFieldSenha.setText(null);
        jLabelCodUsuario.setText(null);
        jRadioButtonAtivo.setSelected(true);
        jTextFieldUsuario.setEnabled(true);
        jTextFieldUsuario.grabFocus();        
    }

    private void AlinhaColunaJTable() {
        int col = 0;
        jTableConsultaUsuario.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Selecionar somente uma linha da JTable
        jTableConsultaUsuario.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); //barra horizontal na JTable 
        jTableConsultaUsuario.getColumnModel().getColumn(col++).setPreferredWidth(50); // Acertar Tamanho de cada coluna
        jTableConsultaUsuario.getColumnModel().getColumn(col++).setPreferredWidth(195);
        jTableConsultaUsuario.getColumnModel().getColumn(col++).setPreferredWidth(20);
        jTableConsultaUsuario.getColumnModel().getColumn(col++).setPreferredWidth(50);

        jTableConsultaUsuario.getColumnModel().getColumn(2).setMaxWidth(0); // Código para deixar uma coluna invisível na jTable
        jTableConsultaUsuario.getColumnModel().getColumn(2).setMinWidth(0);
        jTableConsultaUsuario.getTableHeader().getColumnModel().getColumn(2).setMaxWidth(0);
        jTableConsultaUsuario.getTableHeader().getColumnModel().getColumn(2).setMinWidth(0);
    }

    public void carregardados() {
        jLabelCodUsuario.setText(String.valueOf(ListaUsuario.get(jTableConsultaUsuario.getSelectedRow()).getCod_usuario()));
        jTextFieldUsuario.setText(ListaUsuario.get(jTableConsultaUsuario.getSelectedRow()).getUsuario());
        jPasswordFieldSenha.setText(ListaUsuario.get(jTableConsultaUsuario.getSelectedRow()).getSenha());
        jLabelCodUsuario.setVisible(false);
        
        if("A".equals(ListaUsuario.get(jTableConsultaUsuario.getSelectedRow()).getStatus().trim())){
            jRadioButtonAtivo.setSelected(true);
        } else{
            jRadioButtonInativo.setSelected(true);            
        }
        
        jTextFieldUsuario.setEnabled(false);
    }

    public void validausuariocadastro() {
        String usuario = jTextFieldUsuario.getText().trim();
        String sql = "select usuario from login where usuario = ?";
        try {
            PreparedStatement stmt = this.conexao.prepareStatement(sql);
            stmt.setString(1, usuario);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                JOptionPane.showMessageDialog(null, "Usuário já cadastrado!", "Atenção", JOptionPane.WARNING_MESSAGE);
                limpardados();

            } else {
                cadastro();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void validausuarioaltera() {
        String usuario = jTextFieldUsuario.getText().trim();
        String sql = "select usuario from login where usuario = ?";
        try {
            PreparedStatement stmt = this.conexao.prepareStatement(sql);
            stmt.setString(1, usuario);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                JOptionPane.showMessageDialog(null, "Usuário já cadastrado!", "Atenção", JOptionPane.WARNING_MESSAGE);
                limpardados();

            } else {
                altera();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cadastro() {
        try {
            BeanUsuario BU = new BeanUsuario();
            //BU.setCod_usuario(3);
            BU.setUsuario(jTextFieldUsuario.getText());
            BU.setSenha(jPasswordFieldSenha.getText());

            if (jRadioButtonAtivo.isSelected() == true) {
                BU.setStatus("A");
            } else {
                BU.setStatus("I");
            }
            CRUDUsuario dao = new CRUDUsuario();
            dao.adiciona(BU);
            limpardados();
            listausuario();
            jLabelBarraStatus.setText("Incluido com sucesso!!!");
            threadR(jLabelBarraStatus);
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void altera() {
        BeanUsuario BU = new BeanUsuario();
        BU.setCod_usuario(Integer.valueOf(jLabelCodUsuario.getText()));
        BU.setUsuario(jTextFieldUsuario.getText());
        BU.setSenha(jPasswordFieldSenha.getText());

        if (jRadioButtonAtivo.isSelected() == true) {
            BU.setStatus("A");
        } else {
            BU.setStatus("I");
        }
        CRUDUsuario dao;

        try {
            dao = new CRUDUsuario();
            dao.altera(BU);
            jLabelBarraStatus.setText("Alterado com sucesso!!!");
            limpardados();
            listausuario();
            threadR(jLabelBarraStatus);
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void threadR(final JLabel label) {
        Thread tThread = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
                //repaint();    
                label.setText("");

            }
        });
        tThread.start();
    }

    private void mostraUsuario(List<BeanUsuario> ListaUsuario) {
        if (TMUsuario == null) {
            JOptionPane.showMessageDialog(null, "teste");
        } else {
            while (TMUsuario.getRowCount() > 0) {
                TMUsuario.removeRow(0);
            }
            if (ListaUsuario.size() < 1) {
                //JOptionPane.showMessageDialog(null, "teste2");
            } else {
                String[] linha = new String[]{null, null};
                for (int i = 0; i < ListaUsuario.size(); i++) {
                    TMUsuario.addRow(linha);
                    TMUsuario.setValueAt(ListaUsuario.get(i).getCod_usuario(), i, 0);
                    TMUsuario.setValueAt(ListaUsuario.get(i).getUsuario().trim(), i, 1);
                    TMUsuario.setValueAt(ListaUsuario.get(i).getSenha(), i, 2);
                    
                    if("A".equals(ListaUsuario.get(i).getStatus().trim())){
                        TMUsuario.setValueAt("Ativo", i, 3);                        
                    } else {
                        TMUsuario.setValueAt("Inativo", i, 3);                        
                    }                    
                }
            }
        }
    }
}
